package com.jushu.storbox.database;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.TeamSpaceFileInfo;
import com.jushu.storbox.util.ChinsesCharComp;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class TeamSpaceFileDao extends BaseDao implements ITeamSpaceFileDao {
	public String TABLE_NAME;
	private String mTeamSpaceId;
	public final static String LOG_TAG = "TeamSpaceFileDao";

	/**
	 * 
	 */
	public TeamSpaceFileDao() {
	}
	
	public TeamSpaceFileDao(String tableName){
		TABLE_NAME = tableName;
	}

	
	public String getTeamSpaceId() {
		return mTeamSpaceId;
	}

	public void setTeamSpaceId(String mTeamSpaceId) {
		this.mTeamSpaceId = mTeamSpaceId;
	}

	@Override
	public long insertFile(FileInfoResponseV2 fileInfo) {
		long row = -1;
		try {
			FileInfo fileInfoa = getFileById(fileInfo.getId());
			if(null != fileInfoa && null != fileInfoa.getId() && fileInfoa.getId().trim().equals(fileInfo.getId().trim())){
				LogUtil.e("test1" , "fileDao no need insertFile, id identical");
				return row;
			}
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, fileInfo.getId());
			cv.put(IBaseDao.file_name, fileInfo.getName());
			cv.put(IBaseDao.is_file, 1);
			cv.put(IBaseDao.owner_by, fileInfo.getOwnerBy());
			cv.put(IBaseDao.parent_folder_id, fileInfo.getParent());
			cv.put(IBaseDao.file_md5, fileInfo.getMd5());
			cv.put(IBaseDao.file_size, fileInfo.getSize());
			cv.put(IBaseDao.server_ctime, fileInfo.getCreatedAt());
			cv.put(IBaseDao.server_mtime, fileInfo.getModifiedAt());
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime, fileInfo.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime, fileInfo.getContentModifiedAt());
			cv.put(IBaseDao.static_status, fileInfo.getStatus());
			cv.put(IBaseDao.trans_status, 0);
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.file_true_md5, "");
			cv.put(IBaseDao.local_operation_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.description, fileInfo.getDescription());
			cv.put(IBaseDao.file_etag, fileInfo.getEtag());
			cv.put(IBaseDao.file_sha1, fileInfo.getSha1());
			cv.put(IBaseDao.isencrypt, fileInfo.isEncrypt());
			cv.put(IBaseDao.isshare, fileInfo.isShare());
			cv.put(IBaseDao.isshare_link, fileInfo.isSharelink());
			cv.put(IBaseDao.fileIcon, fileInfo.getThumbnailURL());
			cv.put(IBaseDao.isSync, 0);
			cv.put(IBaseDao.teamspace_id, mTeamSpaceId);
			row = this.getDb().insert(TABLE_NAME, null, cv);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "insertFile fail:" + e.getLocalizedMessage());
		}
		return row;
	}

	@Override
	public void updateFile(FileInfoResponseV2 fileInfoResponse,boolean isSync) {
		try {
			String where = id + " = ? " + " and " + IBaseDao.teamspace_id + " = ? ";
			String[] whereValue = { fileInfoResponse.getId(), mTeamSpaceId };
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, fileInfoResponse.getId());
			cv.put(IBaseDao.file_name, fileInfoResponse.getName());
			cv.put(IBaseDao.is_file, 1);
			cv.put(IBaseDao.owner_by, fileInfoResponse.getOwnerBy());
			cv.put(IBaseDao.parent_folder_id, fileInfoResponse.getParent());
			cv.put(IBaseDao.file_md5, " ");
			cv.put(IBaseDao.file_size, fileInfoResponse.getSize());
			cv.put(IBaseDao.server_ctime, fileInfoResponse.getCreatedAt());
			cv.put(IBaseDao.server_mtime, fileInfoResponse.getModifiedAt());
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime, fileInfoResponse.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime, fileInfoResponse.getContentModifiedAt());
			cv.put(IBaseDao.static_status, fileInfoResponse.getStatus());
			if(isSync){
				cv.put(IBaseDao.trans_status, 0);
			}
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.file_true_md5, "");
			cv.put(IBaseDao.local_operation_time, 5446456);
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.description, fileInfoResponse.getDescription());
			cv.put(IBaseDao.file_etag, fileInfoResponse.getEtag());
			cv.put(IBaseDao.file_sha1, fileInfoResponse.getSha1());
			cv.put(IBaseDao.isencrypt, fileInfoResponse.isEncrypt());
			cv.put(IBaseDao.isshare, fileInfoResponse.isShare());
			cv.put(IBaseDao.isshare_link, fileInfoResponse.isSharelink());
			cv.put(IBaseDao.fileIcon, fileInfoResponse.getThumbnailURL());
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateFile fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateFile(FileInfo fileInfo) {

	}

	@Override
	public void inserOrUpdateFile(FileInfoResponseV2 fileInfo) {

	}

	@Override
	public List<FileInfo> getFileList(String folderId) {
		List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
		Cursor cursor = null;
		try {
			cursor = this.getDb().rawQuery(
					"select * from " + TABLE_NAME + " where "
							+ IBaseDao.parent_folder_id + " = ? " +" and " + IBaseDao.teamspace_id + " = ? " ,
					new String[] { folderId, mTeamSpaceId });
			// 判断游标是否为空
			if (!cursor.moveToFirst()) {
				return fileInfoList;
			}
			do {
				TeamSpaceFileInfo fileInfo = new TeamSpaceFileInfo();
				fileInfoList.add(fileInfo);
			} while (cursor.moveToNext());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileList fail:" + e.getLocalizedMessage());
		}finally{
			if(null != cursor){
				cursor.close();
			}
		}
		return fileInfoList;
	}

	@Override
	public List<FileInfo> getFileListPage(int flag, String folderId) {
		if (null != folderId) {
			int number = ClientConfig.CLOUD_COUNT_PER_PAGE;// 是每次要加载的个数
			int count = ShareDriveApplication.getInstance()
					.getMyCloudDrivePage() * number;// page是加载的页数。
			if (Constant.SHARED_GET_FILE_LIST_STATE == flag) {
				number = ClientConfig.SHARED_COUNT_PER_PAGE;//
				count = ShareDriveApplication.getInstance().getMySharePage()
						* number;// page是加载的页数。
			}
			Cursor cursor = null;
			List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
			try {
				cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + " where "
								+ IBaseDao.parent_folder_id
								+ " = ? and " + IBaseDao.teamspace_id + "= ? " + " Order by server_mtime desc" + " limit ?"
								+ " offset ?",
						new String[] { folderId, mTeamSpaceId,
								String.valueOf(number),
								String.valueOf(count) });
				// 判断游标是否为空
				if (!cursor.moveToFirst()) {
					return fileInfoList;
				}
				do {
					FileInfo fileInfo = new FileInfo();
					fileInfo.fromCursor(cursor);
					fileInfoList.add(fileInfo);
				} while (cursor.moveToNext());
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				LogUtil.e(LOG_TAG, "getFileListPage is fail:" + e.getLocalizedMessage());
			}finally{
				if(null != cursor){
					cursor.close();
				}
			}
			
			return fileInfoList;
		} else {
			LogUtil.e(LOG_TAG, "getFileListPage folderId is null");
		}
		return null;
	}

	@Override
	public List<FileInfo> getFileListPage(int flag, String folderId,
			String des, String orderBy) {
		String dbDes = "DESC";
		String dbOrderBy = "server_mtime";
		if ("DESC".equals(des)) {
			dbDes = "DESC";
		} else {// 升序
			dbDes = "ASC";
		}
		if ("size".equals(orderBy)) {
			dbOrderBy = file_size;
		} else if ("name".equals(orderBy)) {
			return getFileListPageOrderByName(flag, folderId, des, dbOrderBy);
		} else {
			dbOrderBy = server_mtime;
		}
		if (null != folderId) {
			int number = ClientConfig.CLOUD_COUNT_PER_PAGE;// 是每次要加载的个数
			int count = ShareDriveApplication.getInstance()
					.getMyCloudDrivePage() * number;// page是加载的页数。
			if (Constant.SHARED_GET_FILE_LIST_STATE == flag) {
				number = ClientConfig.SHARED_COUNT_PER_PAGE;//
				count = ShareDriveApplication.getInstance().getMySharePage()
						* number;// page是加载的页数。
			}

			List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
			Cursor cursor = null;
			try {
				cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + " where "
								+ IBaseDao.parent_folder_id + " = ? " + "and " + IBaseDao.teamspace_id + " = ? "+ " Order by "
								+ dbOrderBy + " " + dbDes + " limit ?"
								+ " offset ?",
								new String[] { folderId, mTeamSpaceId,
								String.valueOf(number), 
								String.valueOf(count) });
				// 判断游标是否为空
				if (!cursor.moveToFirst()) {
					return fileInfoList;
				}
				do {
					FileInfo fileInfo = new FileInfo();
					fileInfo.fromCursor(cursor);
					fileInfoList.add(fileInfo);
				} while (cursor.moveToNext());
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				LogUtil.e(LOG_TAG, "getFileListPage is fail:" + e.getLocalizedMessage());
			}finally{
				if(null != cursor){
					cursor.close();
				}
			}
			return fileInfoList;
		} else {
			LogUtil.e(LOG_TAG, "folderId is null");
		}
		return null;
	}
	
	@Override
	public List<FileInfo> getFileListPageOrderByName(int flag, String folderId,
			String des, String orderBy) {
		String dbDes = "desc";
		String dbOrderBy = "server_mtime";
		if ("DESC".equals(des)) {
			dbDes = "DESC";
		} else {// 升序
			dbDes = "ASC";
		}
//		if ("size".equals(orderBy)) {
//			dbOrderBy = file_size;
//		} else if ("name".equals(orderBy)) {
//			dbOrderBy = file_name;
//		} else {
//			dbOrderBy = server_mtime;
//		}
		if (null != folderId) {
			int number = ClientConfig.CLOUD_COUNT_PER_PAGE;// 是每次要加载的个数
			int count = ShareDriveApplication.getInstance()
					.getMyCloudDrivePage() * number;// page是加载的页数。
			if (Constant.SHARED_GET_FILE_LIST_STATE == flag) {
				number = ClientConfig.SHARED_COUNT_PER_PAGE;//
				count = ShareDriveApplication.getInstance().getMySharePage()
						* number;// page是加载的页数。
			}

			List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
			Cursor cursor = null;
			try {
				cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + " where "
								+ IBaseDao.parent_folder_id + " = ?" + " and " + IBaseDao.teamspace_id + " = ? " + " Order by "
								+ dbOrderBy + " " + dbDes + " limit ?"
								+ " offset ?",
								new String[] { folderId,
								mTeamSpaceId,
								String.valueOf(number),
								String.valueOf(count) });
				// 判断游标是否为空
				if (!cursor.moveToFirst()) {
					return fileInfoList;
				}
				do {
					FileInfo fileInfo = new FileInfo();
					fileInfo.fromCursor(cursor);
					fileInfoList.add(fileInfo);
				} while (cursor.moveToNext());
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				LogUtil.e(LOG_TAG, "getFileListPage is fail:" + e.getLocalizedMessage());
			}finally{
				if(null != cursor){
					cursor.close();
				}
			}
			
			Iterator<FileInfo> iterator=fileInfoList.iterator();
			List<FileInfo> fileInfoListEn = new ArrayList<FileInfo>();
			List<FileInfo> fileInfoListCn = new ArrayList<FileInfo>();
			while(iterator.hasNext()){
				FileInfo info=iterator.next();
				char[] charOfCN = info.getName().toCharArray();
				if(charOfCN[0]>128){
					fileInfoListCn.add(info);
				}else {
					fileInfoListEn.add(info);
				}
			}
			
			ChinsesCharComp cmp = new ChinsesCharComp();
			cmp.setOrder(dbDes);
			Collections.sort(fileInfoListEn, cmp);
			cmp.setOrder(dbDes);
			Collections.sort(fileInfoListCn, cmp);
			fileInfoList=new ArrayList<FileInfo>();
			if ("DESC".equals(des)) {
				fileInfoList.addAll(fileInfoListEn);
				fileInfoList.addAll(fileInfoListCn);
			}else{
				fileInfoList.addAll(fileInfoListCn);
				fileInfoList.addAll(fileInfoListEn);
			}
			return fileInfoList;
		} else {
			LogUtil.e(LOG_TAG, "folderId is null");
		}
		return null;
	}

	@Override
	public FileInfo getFileById(String fileId) {
		Cursor cursor = null;
		FileInfo fileInfo = null;
		try {
			if (null != fileId) {
				cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + "  where id = ?" +" and " + IBaseDao.teamspace_id + " = ?",
						new String[] { fileId , mTeamSpaceId});
				// 判断游标是否为空
				if (cursor.moveToFirst()) {
					fileInfo = new FileInfo();
					fileInfo.fromCursor(cursor);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileById is fail:" + e.getLocalizedMessage());
		}finally{
			if(null != cursor){
				cursor.close();
			}
		}
		return fileInfo;
	}

	@Override
	public void deleteFile(String fileId) {
		try {
			if (null != fileId) {
				this.getDb().execSQL("delete from " + TABLE_NAME + " where id = ?" + " and " + IBaseDao.teamspace_id + " = ?",
						new String[] { fileId , mTeamSpaceId});
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateLocalPath(String fileId, String localPath) {
		try {
			if (null != fileId) {
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set " + IBaseDao.local_path
								+ " = ? where id = ? and " + IBaseDao.teamspace_id + " = ?",
						new String[] { localPath, fileId , mTeamSpaceId});
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateLocalPath is fail:" + e.getLocalizedMessage());
		}
		
	}

	@Override
	public void updateTransStatus(int status, String fileId) {
		try {
			if (null != fileId) {
				String sql = "update " + TABLE_NAME + "  set "
						+ IBaseDao.trans_status + " = " + status + " where id = "
						+ fileId + " and " + IBaseDao.teamspace_id + " = " + mTeamSpaceId;
				this.getDb().execSQL(sql);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateTransStatus is fail:" + e.getLocalizedMessage());
		}
		
	}
	@Override
	public void updateTransStatusAll(int status) {
		try {
			String sql = "update " + TABLE_NAME + "  set "+ IBaseDao.trans_status + " = " + status;
			this.getDb().execSQL(sql);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateTransStatus is fail:" + e.getLocalizedMessage());
		}
		
	}

	@Override
	public void updateSyncStatus(int syncStatus, String fileId) {
		try {
			String where = id + "=?" + " and " + IBaseDao.teamspace_id + " = ?";
			String[] whereValue = { fileId , mTeamSpaceId};
			ContentValues cv = new ContentValues();
			cv.put(isSync, syncStatus);
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateSyncStatus is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public long getLastUpdateTime(String fileId) {
		long lastUpdateTime = 0;
		Cursor cursor = null;
		try {
			if (null != fileId) {
				cursor = this.getDb().rawQuery(
						"select * from  " + TABLE_NAME + " where id = ?" + " and " + IBaseDao.teamspace_id + " = ?",
						new String[] { fileId, mTeamSpaceId });
				if (cursor.moveToFirst()) {
					lastUpdateTime = cursor.getInt(cursor
							.getColumnIndex(IBaseDao.local_last_modify_time));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getLastUpdateTime is fail:" + e.getLocalizedMessage());
		}finally{
			if(null != cursor){
				cursor.close();
			}
		}
		
		return lastUpdateTime;
	}

	@Override
	public void updateLastUpdateTime(String objectId) {
		try {
			if (null != objectId) {
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set "
								+ IBaseDao.local_last_modify_time
								+ "= ? where id = ?" + " and " + IBaseDao.teamspace_id + " = ?",
								new String[] {
								"" + Calendar.getInstance().getTimeInMillis(),
								objectId , mTeamSpaceId});
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateLastUpdateTime is fail:" + e.getLocalizedMessage());
		}
	}
	public void renameFile(String name, FileInfoResponseV2 fileInfoResponse,String filePath) {
		try {
			if (null != fileInfoResponse.getId()) {
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set " + IBaseDao.file_name
						+ " = ? , "+ IBaseDao.local_path +" = ? , "+IBaseDao.server_mtime + " = ? where id = ?"  + " and " + IBaseDao.teamspace_id + " = ?",
						new String[] { name ,filePath,fileInfoResponse.getModifiedAt()+"",fileInfoResponse.getId() , mTeamSpaceId});
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "renameFile is fail:" + e.getLocalizedMessage());
		}
	}

	/**
	 * 移动（文件）
	 * 
	 * @param context
	 * @param parentID
	 * @param FolderID
	 */
	public void moveFile(String parentID, String FolderID,String filePath) {
		try {
			if (null != FolderID) {
				String sql = "update " + TABLE_NAME + " set "
						+ IBaseDao.parent_folder_id + " = ? , "+IBaseDao.local_path+" = ? where id = ?" +  " and " + IBaseDao.teamspace_id + " = ?";
				this.getDb().execSQL(sql, new String[] { parentID, filePath ,FolderID , mTeamSpaceId});
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "moveFile is fail:" + e.getLocalizedMessage());
		}
	}

	/**
	 * 清楚数据库
	 */
	public void deleteAll() {
		// TODO Auto-generated method stub
		try {
			this.getDb().delete(TABLE_NAME, null, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteAll is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public List<FileFolderInfo> getSearchFileList(String fileName) {
		List<FileFolderInfo> fileInfoList = new ArrayList<FileFolderInfo>();
		Cursor cursor = this.getDb().rawQuery(
				"select * from " + TABLE_NAME + " where " + IBaseDao.file_name
						+ " like ? and " + IBaseDao.teamspace_id + " = " + mTeamSpaceId, new String[] { "%" + fileName + "%" });
		// 判断游标是否为空
		if (!cursor.moveToFirst()) {
			return fileInfoList;
		}
		do {
			FileInfo fileInfo = new FileInfo();
			fileInfo.fromCursor(cursor);
			fileInfoList.add(fileInfo);
		} while (cursor.moveToNext());
		if(null != cursor){
			cursor.close();
		}
		return fileInfoList;
	}

	@Override
	public long insertFile(FileFolderInfo fileInfo) {
		long row = -1;
		try {
			FileInfo fileInfoa = getFileById(fileInfo.getId());
			if(null != fileInfoa && null != fileInfoa.getId() && fileInfoa.getId().trim().equals(fileInfo.getId().trim())){
				LogUtil.e("test1" , "fileDao no need insertFile, id identical");
				return row;
			}
			row = this.getDb().insert(TABLE_NAME, null, fileInfo.toContentValues());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "insertFile fail:" + e.getLocalizedMessage());
		}
		return row;
	}
	
	@Override
	public int getTransStates(String fileId){
		int transStates = -1;
		Cursor cursor = null;
		try {
			cursor = this.getDb().query(TABLE_NAME, new String[]{IBaseDao.trans_status},
					IBaseDao.id + " = ?" + " and "+ IBaseDao.teamspace_id + " = ?",
					new String[]{fileId, mTeamSpaceId}, 
					null,
					null,
					null);
			if(cursor == null){
				return transStates;
			}
			// 判断游标是否为空
			if (!cursor.moveToFirst()) {
				return transStates;
			}
			
			transStates = cursor.getColumnIndex(IBaseDao.trans_status);
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			try {
				cursor.close();
				cursor = null;
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return transStates;
	}


}
